import { createRouter, createWebHistory } from 'vue-router'
import cookie from 'js-cookie'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {//默认跳转主页面
      path: '/',
      redirect: '/index'
    },
    {//主页
      path: '/index',
      name: 'index',
      redirect: '/index/homepage',
      component: () => import('@/views/Index.vue'),
      children: [
        {
          name: 'redirects', path: "redirects/:backpath(.*)", component: () => import('@/views/redirects/index.vue'),
          meta: { 
            title:'homepage'
           }
        },
        {
          name: 'userinfo', path: "userinfo", component: () => import('@/views/admin/UserInfo.vue'),
          meta: { 
            title:'个人信息'
           }
        },
        {
          name: 'changepassword', path: "changepassword", component: () => import('@/views/admin/ChangePassword.vue'),
          meta: { 
            title:'修改密码'
           }
        }
      ]
    },
    {//登录页面
      path: '/login',
      name: 'login',
      component: () => import('@/views/Login.vue')
    },
    {//路径错误重定向404页面
      path: '/:error*',
      redirect: '/404'
    },
    {//404页面
      path: '/404',
      name: '404',
      component: () => import('@/views/404.vue')
    }
  ]
})

router.beforeEach(to=>{
  const token=cookie.get('token')
  if (!token&&to.name!="login") {//除去登录页面,避免进入死循环
    //回到登录页面
    router.replace({path:"/login",query:{back:to.fullPath}});
    return false
  }
  return true
})

export default router
